package com.zhihuishu.micro.course.openapi.manager.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.common.collect.Maps;
import com.zhihuishu.micro.course.dto.ChapterDto;
import com.zhihuishu.micro.course.dto.CourseAuditDto;
import com.zhihuishu.micro.course.dto.LessonDto;
import com.zhihuishu.micro.course.dto.LessonVideoDto;
import com.zhihuishu.micro.course.helper.RedisKeyHelper;
import com.zhihuishu.micro.course.helper.StringHelper;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.model.AppCourseInfo;
import com.zhihuishu.micro.course.model.CourseStatus;
import com.zhihuishu.micro.course.model.CourseTimePlan;
import com.zhihuishu.micro.course.model.CourseVideoForBatis;
import com.zhihuishu.micro.course.model.Lesson;
import com.zhihuishu.micro.course.model.MeetCourse;
import com.zhihuishu.micro.course.model.TblCourse;
import com.zhihuishu.micro.course.openapi.manager.ManagerCourseOpenService;
import com.zhihuishu.micro.course.openapi.manager.dto.AppCourseInfoDto;
import com.zhihuishu.micro.course.openapi.manager.dto.ChapterWebDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CourseOpenDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CoursePendingAuditDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CourseStatusDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CourseTimePlanOpenDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CourseUpdateTimeDto;
import com.zhihuishu.micro.course.openapi.manager.dto.CourseVideoDto;
import com.zhihuishu.micro.course.openapi.manager.dto.LessonVideoWebDto;
import com.zhihuishu.micro.course.openapi.manager.dto.LessonWebDto;
import com.zhihuishu.micro.course.openapi.manager.dto.MeetCourseDto;
import com.zhihuishu.micro.course.openapi.online.CourseOpenService;
import com.zhihuishu.micro.course.service.AppCourseInfoService;
import com.zhihuishu.micro.course.service.ChapterService;
import com.zhihuishu.micro.course.service.CourseAuditService;
import com.zhihuishu.micro.course.service.CourseExtendService;
import com.zhihuishu.micro.course.service.CourseManagementService;
import com.zhihuishu.micro.course.service.CourseService;
import com.zhihuishu.micro.course.service.FirstStepStatService;
import com.zhihuishu.micro.course.service.LessonService;
import com.zhihuishu.micro.course.service.LessonVideoService;
import com.zhihuishu.micro.course.service.MeetCourseService;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.api.APICredential;
import com.zhihuishu.toolkit.helper.BeanHelper;
import com.zhihuishu.toolkit.jedis.template.JedisTemplate;
import com.zhihuishu.toolkit.remote.ResultWrapper;
import com.zhihuishu.user.openapi.common.UserAdvancedQueryOpenService;
import com.zhihuishu.user.openapi.common.UserQueryOpenService;
import com.zhihuishu.user.openapi.common.dto.UserOpenDto;
import com.zhihuishu.user.openapi.common.dto.UserPrivacyOpenDto;

@Service("managerCourseOpenService")
public class ManagerCourseOpenServiceImpl implements ManagerCourseOpenService {
	@Resource
	private CourseService courseService ;
	@Resource
	private ChapterService chapterService ;
	@Resource
	private LessonService lessonService ;
	@Resource
	private CourseAuditService courseAuditService ;
	//@Resource
	//private IUserForCommonRMIService userForCommonRMIService;
	@Resource
	private UserQueryOpenService userQueryOpenService;
	@Resource
	private UserAdvancedQueryOpenService userAdvancedQueryOpenService;
	@Resource
	private CourseManagementService courseManagementService;
	@Resource
	private CourseOpenService courseOpenService ;
//	@Resource
//	private JedisPool jedisPool ;
	@Resource
	private CourseExtendService courseExtendService ;
	@Resource
	private MeetCourseService meetCourseService;
	@Resource
	private LessonVideoService lessonVideoService ;
	@Resource
	private AppCourseInfoService appCourseInfoService;
	@Resource
	private FirstStepStatService firstStepStatService;
	@Resource
	private APICredential apiCredential;
    @Resource
    private JedisTemplate jedisTemplate;
	
	@Override
	public RemoteResult<List<CourseOpenDto>> findCourseOpenDtos(int count)
			throws RemoteException {
		RemoteResult<List<CourseOpenDto>> result = new RemoteResult<List<CourseOpenDto>>() ;
		try {
			List<CourseAuditDto> courseList = courseAuditService.findCourseOpenDtos(count);
			List<CourseOpenDto> list = null;
			if(!CollectionUtils.isEmpty(courseList)){
				list = new ArrayList<CourseOpenDto>();
				CourseOpenDto courseOpenDto = null;
				for(CourseAuditDto courseAuditDto :courseList){
//					courseOpenDto = BeanHelper.transTo(courseAuditDto, CourseOpenDto.class); //速度有些慢
					courseOpenDto = new CourseOpenDto();
					courseOpenDto.setCourseId(courseAuditDto.getCourseId());
					courseOpenDto.setUserId(courseAuditDto.getUserId());
					courseOpenDto.setName(courseAuditDto.getName());
					courseOpenDto.setIntroduction(courseAuditDto.getIntroduction());
					courseOpenDto.setApprovalQueryStatus(courseAuditDto.getApprovalQueryStatus());
					courseOpenDto.setApprovalResultStatus(courseAuditDto.getApprovalResultStatus());
					courseOpenDto.setApprovalResultTime(courseAuditDto.getApprovalResultTime());
					courseOpenDto.setCreateTime(courseAuditDto.getCreateTime());
					courseOpenDto.setUpdateTime(courseAuditDto.getUpdateTime());
					courseOpenDto.setCourseTag(courseAuditDto.getCourseTag());
					courseOpenDto.setTeamData(courseAuditDto.getTeamData());
					courseOpenDto.setTeachingProgram(courseAuditDto.getTeachingProgram());
					courseOpenDto.setTeachingPlan(courseAuditDto.getTeachingPlan());
					courseOpenDto.setMoiveDesc(courseAuditDto.getMoiveDesc());
					list.add(courseOpenDto);
				}
				result.setResult(list) ;
			}
			
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询审计课程内容出错!") ;
		}
		
		return result ;
	}

	@Override
	public RemoteResult<Boolean> updateCourseOpenDtos(
			List<CourseOpenDto> courseOpenDtoList) throws RemoteException {
		RemoteResult<Boolean> result = new RemoteResult<Boolean>() ;
		try {
			if(!CollectionUtils.isEmpty(courseOpenDtoList)){
				List<CourseAuditDto> courseList = new ArrayList<CourseAuditDto>();
				CourseAuditDto courseAuditDto = null;
				StringBuffer courseIds = new StringBuffer();
				for(CourseOpenDto courseOpenDto:courseOpenDtoList){
					if(courseOpenDto.getCourseId()!=null){
						courseAuditDto =  BeanHelper.transTo(courseOpenDto, CourseAuditDto.class);
						courseList.add(courseAuditDto);
						courseIds.append(courseAuditDto.getCourseId()+",");
					}
				}
				Boolean flag = courseAuditService.updateCourseOpenDtos(courseList);
				LoggerTemplateUtil.saveLogger(String.format("更新审计课程内容,courseIds=%s", courseIds.toString()), 0L, LoggerCollectionEnum.courseCollection);
				result.setResult(flag) ;
			}
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("修改审计课程内容出错!") ;
		}
		return result ;
	}

	@Override
	public RemoteResult<Integer> findPendingAuditCourseAmount(String courseName)
			throws RemoteException {
		RemoteResult<Integer> result = new RemoteResult<Integer>();
		try {
			Integer courseAmount = courseAuditService.findPendingAuditCourseAmount(courseName);
			result.setResult(courseAmount);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询待审核课程总数量出错!") ;
		}
		return result;
	}

	@Override
	public RemoteResult<List<CoursePendingAuditDto>> findPendingAuditCourseDtos(
			String courseName, int pageNo, int pageSize) throws RemoteException {
		RemoteResult<List<CoursePendingAuditDto>> result = new RemoteResult<List<CoursePendingAuditDto>>();
		try {
			if (pageNo < 1 || pageSize < 1 || courseName == null) {
				result.setSuccess(false);
				result.setExceptionStack(new Exception("参数不合法（courseName不为null，pageNo、pageSiz大于0）"));
				result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
				return result;
			}
			List<TblCourse> tblCourses = courseAuditService.findPendingAuditCourseDtos(courseName, pageNo, pageSize);
			List<CoursePendingAuditDto> courseDtos = null;
			if (tblCourses != null && tblCourses.size() > 0) {
				courseDtos = new ArrayList<CoursePendingAuditDto>();
				for (TblCourse tblCourse : tblCourses) {
					CoursePendingAuditDto dto = new CoursePendingAuditDto();
					dto.setCourseId(tblCourse.getCourseId());
					dto.setCourseOpener(tblCourse.getCourseOpener());
					dto.setCreateTime(tblCourse.getCreateTime());
					dto.setImg(tblCourse.getImg());
					dto.setIntroduction(tblCourse.getIntroduction());
					dto.setName(tblCourse.getName());
					//调用user接口查询teacherName，避免tbl_course表中teacher_name为空及用户修改了realName课程表中未同步的情况
					//CommonUserRMIDto userDto = userForCommonRMIService.findUserInfoById(tblCourse.getMajorSpeaker());
					ResultWrapper<UserOpenDto> resultWrapper = userQueryOpenService.get(tblCourse.getMajorSpeaker());
					UserOpenDto userOpenDto = resultWrapper.getResult();
					//dto.setTeacherName(userDto != null ?userDto.getRealName() : "");
					dto.setTeacherName(userOpenDto != null ?userOpenDto.getRealname() : "");
					if (tblCourse.getCcCourse() != null) {
						dto.setTags(tblCourse.getCcCourse().getCourseTag());
//						dto.setTeachingPlan(tblCourse.getCcCourse().getTeachingPlan());
//						dto.setTeachingProgram(tblCourse.getCcCourse().getTeachingProgram());
						dto.setTeamData(tblCourse.getCcCourse().getTeamData());
					}
					courseDtos.add(dto);
				}
			}
			result.setResult(courseDtos);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询待审核课程信息列表出错!") ;
		}
		return result;
	}

	@Override
	public RemoteResult<List<ChapterWebDto>> findChapterList(Long courseId)
			throws RemoteException {
		RemoteResult<List<ChapterWebDto>> result = new RemoteResult<List<ChapterWebDto>>() ;
		if(courseId==null){
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}
		try {
			List<ChapterDto> chapterList = chapterService.list(courseId);
			List<ChapterWebDto> list = null;
			if(!CollectionUtils.isEmpty(chapterList)){
				list = new ArrayList<ChapterWebDto>();
				ChapterWebDto chapterWebDto = null;
				for(ChapterDto chapter : chapterList){
					chapterWebDto = new ChapterWebDto();
					chapterWebDto.setId(chapter.getId());
					chapterWebDto.setName(chapter.getName());
					chapterWebDto.setDescription(chapter.getDescription());
					chapterWebDto.setOrderNumber(chapter.getRank());
					List<Lesson> lessonList = courseAuditService.findLessonlistByChapterId(chapter.getId());
					if(!CollectionUtils.isEmpty(lessonList)){
						List<LessonWebDto> lessons = new ArrayList<LessonWebDto>();
						LessonWebDto lessonWebDto = null;
						for(Lesson lesson:lessonList){
							lessonWebDto = new LessonWebDto();
							lessonWebDto.setId(lesson.getId());
							lessonWebDto.setName(lesson.getName());
							lessonWebDto.setDescription(lesson.getIntroduction());
							lessonWebDto.setOrderNumber(lesson.getOrderNumber());
							lessons.add(lessonWebDto);
						}
						chapterWebDto.setLessons(lessons);
					}
					list.add(chapterWebDto);
				}
				result.setResult(list) ;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询审计章节内容出错!") ;
		}
		
		return result ;

	}

	@Override
	public RemoteResult<Integer> findCourseDtoTotalCount(String keywords, Long userId) throws RemoteException {
		RemoteResult<Integer> result = new RemoteResult<Integer>();
		try {
			Integer totalCount = courseManagementService.findCourseDtoTotalCount(keywords, userId);
			result.setResult(totalCount);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询课程总数出错!") ;
		}
		return result;
	}

	@Override
	public RemoteResult<List<CourseOpenDto>> findPageCourseDtos(String keywords, int pageNo, int pageSize, Long userId) throws RemoteException {
		RemoteResult<List<CourseOpenDto>> result = new RemoteResult<List<CourseOpenDto>>();
		if (pageSize==0) {
			result.setSuccess(false);
			result.setExceptionStack(new Exception("参数不合法:分页条数pageSize为0！"));
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result;
		}
		try {
			List<CourseOpenDto> courseOpenDtos = null;
			List<TblCourse> tblCourses = courseManagementService.findPageCourseDtos(keywords, pageNo, pageSize, userId);
			if(tblCourses!=null&&tblCourses.size()>0){
				courseOpenDtos = new ArrayList<CourseOpenDto>();
				CourseOpenDto dto = null;
				for(TblCourse course:tblCourses){
					dto = new CourseOpenDto();
					dto.setCourseId(course.getCourseId());
					dto.setCourseModel(course.getCourseMode());
					dto.setName(course.getName());
					//CommonUserRMIDto userDto = userForCommonRMIService.findUserInfoById(course.getMajorSpeaker());
					ResultWrapper<UserOpenDto> resultWrapper = userQueryOpenService.get(course.getMajorSpeaker());
					UserOpenDto userOpenDto = resultWrapper.getResult();
					//dto.setCourseTeacher(userDto != null ?userDto.getRealName() : "");
					dto.setCourseTeacher(userOpenDto != null ?userOpenDto.getRealname(): "");
					dto.setCredit(course.getCredit());
					dto.setCourseTime(course.getCourseTime());
					dto.setHoursOffline(course.getHoursOffline());
					dto.setHoursOnline(course.getHoursOnline());
					dto.setSchoolName(course.getSchoolName());
					dto.setVideoSource(course.getVideoSource());
					courseOpenDtos.add(dto);
				}
			}
			result.setResult(courseOpenDtos);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询课程分页列表数据出错!") ;
		}
		
		return result;
	}

	@Override
	public RemoteResult<Map<Long, Integer>> findProgressByCourseIds(List<Long> courseIds) throws RemoteException {
		RemoteResult<Map<Long, Integer>> result = new RemoteResult<Map<Long, Integer>>();
		if (courseIds==null||courseIds.size()==0) {
			result.setSuccess(false);
			result.setExceptionStack(new Exception("参数不合法:courseIds为null！"));
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result;
		}
        //变形虫不支持批量sql
		try {
			Map<Long, Integer> map = new HashMap<Long,Integer>();
//			for(Long courseId:courseIds){
//				if(courseId!=null){
//					TblCourse course = courseManagementService.findCourseOpenByCourseId(courseId);
//					if(course!=null){
//						if(course.getVersion()==null){
//							if(course.getCreateStep()!=null){
//								map.put(courseId, (int) Math.rint(course.getCreateStep()*100.0/5));
//							}
//						}else{
//							if(course.getCreateStep()!=null){
//								map.put(courseId, (int) Math.rint(course.getCreateStep()*100.0/6));
//							}
//						}
//					}
//					
//				}
//			}
			RemoteResult<Map<Long, Map<String, Integer>>> progressResult = courseOpenService.findProgressByCourseIds(courseIds);
			Map<Long, Map<String, Integer>> progressMap = progressResult.getResult();
			if(progressMap!=null&&progressMap.size()>0){
				for(Long courseId:progressMap.keySet()){
					if(progressMap.get(courseId)!=null){
						map.put(courseId, progressMap.get(courseId).get("progress"));
					}
				}
			}
			result.setResult(map);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询进度出错!") ;
		}
		
		return result;
	}

	@Override
	public RemoteResult<List<CourseTimePlanOpenDto>> findCourseTimePlanByCourseId(Long courseId) throws RemoteException {
		RemoteResult<List<CourseTimePlanOpenDto>> result = new RemoteResult<List<CourseTimePlanOpenDto>>();
		if (courseId==null) {
			result.setSuccess(false);
			result.setExceptionStack(new Exception("参数不合法:courseId为null！"));
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result;
		}
		try {
			List<CourseTimePlanOpenDto> courseTimePlanOpenDtos = null;
			List<CourseTimePlan> courseTimePlans = courseManagementService.findCourseTimePlanByCourseId(courseId);
			if(courseTimePlans!=null&&courseTimePlans.size()>0){
				courseTimePlanOpenDtos = new ArrayList<CourseTimePlanOpenDto>();
				CourseTimePlanOpenDto dto = null;
				for(CourseTimePlan model:courseTimePlans){
					dto = new CourseTimePlanOpenDto();
					dto.setId(model.getId());
					dto.setCourseId(model.getCourseId());
					dto.setItem(model.getItem());
					dto.setChargeMan(model.getCharegeMan());
					if(model.getPlanFinishTime()!=null){
						dto.setPlanFinishTime(new SimpleDateFormat("yyyy-MM-dd").format(model.getPlanFinishTime()));
					}
					dto.setOutPut(model.getOutPut());
					dto.setOrderNumber(model.getOrderNumber());
					courseTimePlanOpenDtos.add(dto);
				}
			}
			result.setResult(courseTimePlanOpenDtos);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询课程计划表接口出错!") ;
		}
		return result;
	}

	@Override
	public RemoteResult<CourseOpenDto> findCourseOpenByCourseId(Long courseId)
			throws RemoteException {
		RemoteResult<CourseOpenDto> result = new RemoteResult<CourseOpenDto>();
		if (courseId==null) {
			result.setSuccess(false);
			result.setExceptionStack(new Exception("参数不合法:courseId为null！"));
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result;
		}
//		Jedis jedis = null ;
		try {
			TblCourse course = courseManagementService.findCourseOpenByCourseId(courseId);
			CourseOpenDto dto = null;
			if(course!=null){
				dto = new CourseOpenDto();
				dto.setCourseId(course.getCourseId());
				dto.setCourseModel(course.getCourseMode());
				dto.setName(course.getName());
				//CommonUserRMIDto userDto = userForCommonRMIService.findUserInfoById(course.getMajorSpeaker());
				ResultWrapper<UserOpenDto> resultWrapper = userQueryOpenService.get(course.getMajorSpeaker());
				UserOpenDto userOpenDto = resultWrapper.getResult();
				//dto.setCourseTeacher(userDto != null ?userDto.getRealName() : "");
				dto.setCourseTeacher(userOpenDto != null ?userOpenDto.getRealname() : "");				
				dto.setCredit(course.getCredit());
				dto.setCourseTime(course.getCourseTime());
				dto.setHoursOffline(course.getHoursOffline());
				dto.setHoursOnline(course.getHoursOnline());
				dto.setSchoolName(course.getSchoolName());
				dto.setVideoSource(course.getVideoSource());
				//dto.setCourseVersion(2);
//				jedis = this.jedisPool.getResource() ;
				String key = RedisKeyHelper.courseVersionKey(courseId);
				String version = jedisTemplate.hget(key, "version");
				if(version==null){
	    			int count = courseService.findCourseStepStatCount(courseId); //新版建课存储进度数据
	    			if(count==0){
	    				version = "1";
	    			}else{
	    				version = "2";
	    			}
	    			Map<String ,String> hash = new HashMap<String, String>() ;
	        		hash.put("version", version);
	        		jedisTemplate.hmset(key, hash);
	    		}
				dto.setCourseVersion(Integer.parseInt(version));
				dto.setCourseBackGround(course.getCourseBackGround());
				dto.setCourseTarget(course.getCourseTarget());
				dto.setIntroduction(course.getIntroduction());
				dto.setVideoId(course.getVideoId());
				dto.setMoiveDesc(course.getMovieDesc());
				List<Long> courseIds = new ArrayList<Long>();
				courseIds.add(courseId);
				RemoteResult<Map<Long, Map<String, Integer>>> progressResult = courseOpenService.findProgressByCourseIds(courseIds);
				Map<Long, Map<String, Integer>> progressMap = progressResult.getResult();
				if(progressMap!=null&&progressMap.size()>0){
					if(progressMap.get(courseId)!=null){
						dto.setProgress(progressMap.get(courseId).get("progress"));
					}
				}
			}
			result.setResult(dto);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询课程信息表接口出错!") ;
		} finally {
//			JedisHelper.closeQuietly(jedis);
		}
		return result;
	}

	@Override
	public RemoteResult<Map<Long, CourseStatusDto>> findCoursesStatus(List<Long> courseIds) {
		RemoteResult<Map<Long, CourseStatusDto>> remoteResult=new RemoteResult<Map<Long,CourseStatusDto>>();
		Map<Long, CourseStatusDto> map=Maps.newHashMap();
		CourseStatusDto courseStatusDto=null;
		try {
			Assert.notNull(courseIds,"课程列表集合不能为空");
			Assert.notEmpty(courseIds, "课程id列表集合不能为空");
			List<CourseStatus> courseStatus=courseService.findCoursesStatus(courseIds);
			//if (courseStatus!=null&&courseStatus.size()>0) {
				for (CourseStatus tmp : courseStatus) {
					courseStatusDto=new CourseStatusDto();
					BeanUtils.copyProperties(tmp, courseStatusDto);
					map.put(courseStatusDto.getCourseId(), courseStatusDto);
				}
				for (Long tempCourseId : courseIds) {
					if (map.containsKey(tempCourseId)) {//新版
						map.get(tempCourseId).setCourseType(1);
					}else {//老版
						courseStatusDto=new CourseStatusDto();
						courseStatusDto.setCourseType(2);
						courseStatusDto.setCourseId(tempCourseId);
						map.put(tempCourseId, courseStatusDto);
					}
				}
				remoteResult.setResult(map);
			//}			
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}

	@Override
	public RemoteResult<List<CourseUpdateTimeDto>> findCourseUpdateTime(List<Long> courseIds) {
		RemoteResult<List<CourseUpdateTimeDto>> remoteResult=new RemoteResult<List<CourseUpdateTimeDto>>();
		if (courseIds==null || courseIds.size() == 0) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(new Exception("参数不合法:传入参数为null！"));
			remoteResult.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return remoteResult;
		}
		List<CourseUpdateTimeDto> dtoList = new ArrayList<CourseUpdateTimeDto>();
		
		try {
			//查询 课程背景  更新时间
			List<Map<String, Object>> backGroundUpdateTimeList = courseExtendService.getUpdateTimeByCourseIdsAndKey(courseIds,StringHelper.camelToUnderscore("courseBackground"));
			//查询 课程目标  更新时间
			List<Map<String, Object>> targetUpdateTimeList = courseExtendService.getUpdateTimeByCourseIdsAndKey(courseIds,StringHelper.camelToUnderscore("courseTarget"));
			//查询 课程名、课程设计原则、课程设计原则更新时间、课程推广推荐词、课程推广片花ID、课程推广更新时间
			List<TblCourse> introductionAndMovieClipsList = courseService.getCourseIntroductionAndMovieClipsInfo(courseIds);
			//查询 课程时间计划  更新时间
			List<Map<String, Object>> courseTimePlanUpdateTimeList = courseManagementService.getcourseTimePlanUpdateTimeByCourseIds(courseIds);
			//查询 见面课  更新时间
			List<Map<String, Object>> meetCourseUpdateTimeList = meetCourseService.getMeetCourseUpdateTimeByCourseIds(courseIds);
			//查询 课程是新版还是老版
			List<Map<String, Object>> courseVersionList = firstStepStatService.countByCourseIds(courseIds);
			
			for (Long courseId : courseIds) {
				Assert.notNull(courseId,"课程ID不能为空");
				CourseUpdateTimeDto courseUpdateTimeDto = new CourseUpdateTimeDto();
				courseUpdateTimeDto.setCourseId(courseId);
				//查询课程背景、课程目标更新时间
				for (Map<String, Object> map : backGroundUpdateTimeList) {
					if (courseId.equals(Long.parseLong(map.get("courseId").toString()))) {
						if (map.get("updateTime") != null) {
							courseUpdateTimeDto.setCourseBackgroundTime((Date)map.get("updateTime"));
						}
					}
				}
				for (Map<String, Object> map : targetUpdateTimeList) {
					if (courseId.equals(Long.parseLong(map.get("courseId").toString()))) {
						if (map.get("updateTime") != null) {
							courseUpdateTimeDto.setCourseTargetTime((Date)map.get("updateTime"));
						}
					}
				}
				//查询课程设计原则及设计原则更新时间
				if (introductionAndMovieClipsList != null && introductionAndMovieClipsList.size() > 0) {
					for (TblCourse course : introductionAndMovieClipsList) {
						if (courseId.equals(course.getCourseId())) {
							courseUpdateTimeDto.setCourseName(course.getName());
							if (StringUtils.isNotBlank(course.getIntroduction())) {
								courseUpdateTimeDto.setCourseDesignTime(course.getUpdateTime() == null ? course.getCreateTime() : course.getUpdateTime());
								courseUpdateTimeDto.setCourseDesign(course.getIntroduction());
							}
							if (course.getCcCourse() != null && (course.getCcCourse().getMoiveDesc()!=null || course.getCcCourse().getVideoId()!=null)) {
								courseUpdateTimeDto.setCourseAdviseContent(course.getCcCourse().getMoiveDesc());
								courseUpdateTimeDto.setCourseAdviseTime(
										course.getCcCourse().getUpdateTime() == null ? course.getCcCourse().getCreateTime() : course.getCcCourse().getUpdateTime());
								courseUpdateTimeDto.setCourseAdviseVedioId(course.getCcCourse().getVideoId());
							}
						}
					}
				}
				//查询课程时间计划更新时间
				for (Map<String, Object> map : courseTimePlanUpdateTimeList) {
					if (courseId.equals(Long.parseLong(map.get("courseId").toString()))) {
						if (map.get("updateTime") != null) {
							courseUpdateTimeDto.setCoursePlanTime((Date)map.get("updateTime"));
						}
					}
				}
				//查询见面课更新时间
				for (Map<String, Object> map : meetCourseUpdateTimeList) {
					if (courseId.equals(Long.parseLong(map.get("courseId").toString()))) {
						if (map.get("updateTime") != null) {
							courseUpdateTimeDto.setMeetCourseTime((Date)map.get("updateTime"));
						}
					}
				}
				//查询课程新/老版本
				courseUpdateTimeDto.setVersion(1);
				for (Map<String, Object> map : courseVersionList) {
					if (courseId.equals(Long.parseLong(map.get("courseId").toString()))) {
						if (map.get("dataCount") != null && Integer.parseInt(map.get("dataCount").toString()) > 0) {
							courseUpdateTimeDto.setVersion(2);
						}
					}
				}
				dtoList.add(courseUpdateTimeDto);
			}
			remoteResult.setResult(dtoList);
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}

	@Override
	public RemoteResult<List<CourseVideoDto>> findCourseVideo(List<Long> courseIds) throws RemoteException {
		RemoteResult<List<CourseVideoDto>> remoteResult=new RemoteResult<List<CourseVideoDto>>();
		if (courseIds==null || courseIds.size() == 0) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(new Exception("参数不合法:传入参数为null！"));
			remoteResult.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return remoteResult;
		}
		try {
			//查询节
			List<CourseVideoForBatis> lessonDtoList = lessonService.getLessonByCourseIds(courseIds);
			//查询小节
			List<CourseVideoForBatis> smallLessonDtoList = lessonVideoService.getSmallLessonByCourseIds(courseIds);
			List<CourseVideoDto> dtoList = new ArrayList<CourseVideoDto>();
			CourseVideoDto courseVideoDto = null;
			for (CourseVideoForBatis courseVideoForBatis : lessonDtoList) {
				courseVideoDto = BeanHelper.transTo(courseVideoForBatis, CourseVideoDto.class);
				courseVideoDto.setSamllLesson(false);
				dtoList.add(courseVideoDto);
			}
			for (CourseVideoForBatis courseVideoForBatis : smallLessonDtoList) {
				courseVideoDto = BeanHelper.transTo(courseVideoForBatis, CourseVideoDto.class);
				courseVideoDto.setSamllLesson(true);
				dtoList.add(courseVideoDto);
			}
			remoteResult.setResult(dtoList);
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}

	@Override
	public RemoteResult<List<MeetCourseDto>> findMeetCourse(Long courseId) throws RemoteException {
		RemoteResult<List<MeetCourseDto>> remoteResult=new RemoteResult<List<MeetCourseDto>>();
		if (courseId==null) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(new Exception("参数不合法:传入参数为null！"));
			remoteResult.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return remoteResult;
		}
		try {
			//查询见面课列表
			List<MeetCourse> meetCourseList = meetCourseService.getMeetCourseByCourseId(courseId);
			List<MeetCourseDto> dtoList = null;
			if (meetCourseList!= null && meetCourseList.size() > 0) {
				dtoList = new ArrayList<MeetCourseDto>();
				for (MeetCourse meetCourse : meetCourseList) {
					MeetCourseDto meetCourseDto = new MeetCourseDto();
					meetCourseDto.setItem(meetCourse.getCourseTopic());
					meetCourseDto.setStartWeek(meetCourse.getEst());
					meetCourseDto.setTeacher(meetCourse.getSpeakerName());
					meetCourseDto.setType(meetCourse.getTaskType());
					meetCourseDto.setRequest(meetCourse.getTeachRequire());
					meetCourseDto.setRequestProgress(meetCourse.getReqProgress());
					dtoList.add(meetCourseDto);
				}
			}
			remoteResult.setResult(dtoList);
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}

	@Override
	public RemoteResult<Integer> findAppCourseInfoTotalCount(String keywords)
			throws RemoteException {
		RemoteResult<Integer> result = new RemoteResult<Integer>();
		try {
			Integer totalCount = appCourseInfoService.findAppCourseInfoTotalCount(keywords);
			result.setResult(totalCount);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询app课程信息总数出错!") ;
		}
		return result;
	}

	@Override
	public RemoteResult<List<AppCourseInfoDto>> findPageAppCourseInfoDtos(String keywords, int pageNo, int pageSize) throws RemoteException {
		RemoteResult<List<AppCourseInfoDto>> result = new RemoteResult<List<AppCourseInfoDto>>();
		try {
			List<AppCourseInfoDto> dtos = null;
			List<AppCourseInfo> appCourseInfoList = appCourseInfoService.findPageAppCourseInfoDtos(keywords, pageNo, pageSize);
			if(!CollectionUtils.isEmpty(appCourseInfoList)){
				dtos = new ArrayList<AppCourseInfoDto>();
				AppCourseInfoDto dto = null;
				for(AppCourseInfo model:appCourseInfoList){
					dto = new AppCourseInfoDto();
					dto.setId(model.getId());
					dto.setCourseId(model.getCourseId());
					dto.setCourseName(model.getCourseName());
					dto.setUserId(model.getUserId());
					dto.setUserName(model.getUserName());
					//CommonUserRMIDto userDto = userForCommonRMIService.findUserInfoById(model.getUserId());
					ResultWrapper<UserPrivacyOpenDto> resultWrapper = userAdvancedQueryOpenService.get(apiCredential, model.getUserId());
					UserPrivacyOpenDto userPrivacyOpenDto = resultWrapper.getResult();
					//dto.setPhoneNumber(userDto!=null?userDto.getPhoneNumber():null);
					dto.setPhoneNumber(userPrivacyOpenDto!=null?userPrivacyOpenDto.getMobile():null);
					dto.setSchoolName(model.getSchoolName());
					dto.setCreateTime(model.getCreateTime());
					dto.setUpdateTime(model.getUpdateTime());
					dtos.add(dto);
				}
			}
			result.setResult(dtos);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询app课程信息列表出错!") ;
		}
		return result;
		
	}

	@Override
	public RemoteResult<List<ChapterWebDto>> findChapterAndLessonByCourseId(Long courseId) throws RemoteException {
		RemoteResult<List<ChapterWebDto>> remoteResult=new RemoteResult<List<ChapterWebDto>>();
		if (courseId==null) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(new Exception("参数不合法:传入参数为null！"));
			remoteResult.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return remoteResult;
		}
		try {
			List<ChapterWebDto> resultList = null;
			//查询章列表
			List<ChapterDto> chapterList = chapterService.getChapterListFromDb(courseId);
			if (chapterList != null && chapterList.size() > 0) {
				resultList = new ArrayList<ChapterWebDto>();
				for (ChapterDto chapterDto : chapterList) {
					ChapterWebDto chapterWebDto = new ChapterWebDto();
					chapterWebDto.setId(chapterDto.getId());
					chapterWebDto.setName(chapterDto.getName());
					chapterWebDto.setOrderNumber(chapterDto.getRank());
					//查询节列表
					List<LessonDto> lessonList = lessonService.getLessonListFromDb(chapterDto.getId());
					if (lessonList != null && lessonList.size() > 0) {
						List<LessonWebDto> lessonWebDtoList = new ArrayList<LessonWebDto>();
						for (LessonDto lessonDto : lessonList) {
							LessonWebDto lessonWebDto = new LessonWebDto();
							lessonWebDto.setId(lessonDto.getId());
							lessonWebDto.setName(lessonDto.getName());
							lessonWebDto.setOrderNumber(lessonDto.getRank());
							lessonWebDto.setVideoId(lessonDto.getVideoId());
							lessonWebDto.setVideoSize(videoSecToVideoSize(lessonDto.getVideoSec()));
							if (lessonDto.getHaveChildren() > 0) {
								//查询小节列表
								List<LessonVideoDto> lessonVideoList = lessonVideoService.getLessonVideoListFromDb(lessonDto.getId());
								if (lessonVideoList!=null && lessonVideoList.size() > 0) {
									List<LessonVideoWebDto> lessonVideoWebDtoList = new ArrayList<LessonVideoWebDto>();
									for (LessonVideoDto lessonVideoDto : lessonVideoList) {
										LessonVideoWebDto lessonVideoWebDto = new LessonVideoWebDto();
										lessonVideoWebDto.setId(lessonVideoDto.getId());
										lessonVideoWebDto.setOrderNumber(lessonVideoDto.getRank());
										lessonVideoWebDto.setName(lessonVideoDto.getName());
										lessonVideoWebDto.setVideoId(lessonVideoDto.getVideoId() == null ? null : Integer.parseInt(lessonVideoDto.getVideoId()+""));
										lessonVideoWebDto.setVideoSize(videoSecToVideoSize(lessonVideoDto.getVideoSec()));
										lessonVideoWebDtoList.add(lessonVideoWebDto);
									}
									lessonWebDto.setLessonVideos(lessonVideoWebDtoList);
								}
							}
							lessonWebDtoList.add(lessonWebDto);
						}
						chapterWebDto.setLessons(lessonWebDtoList);
					}
					resultList.add(chapterWebDto);
				}
			}
			remoteResult.setResult(resultList);
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}
	
	/**
	 * 视频时长转换：秒数→xx:xx:xx
	 * @author ztl
	 * @param videoSec
	 * @return
	 */
	private String videoSecToVideoSize (Long videoSec) {
		if (videoSec == null) {
			return null;
		}
		int hour = (int) (videoSec/3600);
		int min = (int) ((videoSec%3600)/60);
		int sec = (int) ((videoSec%3600)%60);
		return hour+":"+min+":"+sec;
	}
}
